
/**
 * @name MassWG (MASS Wind Gradient 1) Calculates surface moisture flux for
 * January 2-31, 1980 Part of Pacific Northwest Climate Data Analysis
 *
 * @version 0.1.504 Alpha, MASS Wind Gradient 1, 4th commit
 * @date 10/4/2013
 * @author Niko Simonson
 * @author Brett Yasutake
 */
import java.awt.*;
import java.awt.Graphics;
import ucar.nc2.NetcdfFile;     // for netCDF reader
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import ucar.ma2.ArrayDouble;
import ucar.ma2.IndexIterator;
import ucar.nc2.Variable;

/**
 * @name ResultsViewer
 */
public class ResultsViewer extends javax.swing.JFrame {

    private resultsChooser chooser;
    private UIPrototype1 ui;
    public NetcdfFile inFile;
    public Graphics graphics;
    public Color[] rvColor;
    public int[] dimensions;

    public void setFile(String location) {
        try {
            inFile = NetcdfFile.openInMemory(location);
            dimensions = new int[inFile.getDimensions().size()];

            Iterator<ucar.nc2.Dimension> it = inFile.getDimensions().iterator();

            int counter = 0;
            while (it.hasNext()) {
                dimensions[counter] = it.next().getLength();
                ++counter;
            }

        } catch (IOException ex) {
            Logger.getLogger(ResultsViewer.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.err.println("Success");
        startGraphics();
        System.err.println("Started Graphics");

        rvPanel = new RVPanel(this);
        rvPanel.setSize(300, 300);
        rvPanel.setVisible(true);
        Container container = getContentPane();
        rvPanel.setVisible(true);
        container.add(rvPanel);
        rvPanel.setVisible(true);
        container.validate();
        rvPanel.setVisible(true);

//        graphics = rvPanel.getGraphics();
//        this.paintAll(graphics);
        System.err.println("Done");
    }

    public void startGraphics() {
        // prepare cell colors
        rvColor = new Color[21];
        rvColor[0] = new Color(0x0000FF);   // blue
        rvColor[1] = new Color(0x0033FF);
        rvColor[2] = new Color(0x0066FF);
        rvColor[3] = new Color(0x0099FF);
        rvColor[4] = new Color(0x00CCFF);
        rvColor[5] = new Color(0x00FFFF);
        rvColor[6] = new Color(0x00FFCC);
        rvColor[7] = new Color(0x00FF99);
        rvColor[8] = new Color(0x00FF66);
        rvColor[9] = new Color(0x00FF33);
        rvColor[10] = new Color(0x00FF00);  // green
        rvColor[11] = new Color(0x33FF00);
        rvColor[12] = new Color(0x66FF00);
        rvColor[13] = new Color(0x99FF00);
        rvColor[14] = new Color(0xCCFF00);
        rvColor[15] = new Color(0xFFFF00);
        rvColor[16] = new Color(0xFFCC00);
        rvColor[17] = new Color(0xFF9900);
        rvColor[18] = new Color(0xFF6600);
        rvColor[19] = new Color(0xFF3300);
        rvColor[20] = new Color(0xFF0000);  // red

    }

    /**
     * @name drawGraphics
     */
    private void drawGraphics() {
        Variable values;
        ArrayDouble.D2 ary;
        values = inFile.getVariables().get(0);
        double min = 0.0, max = 0.0;
        double[][] vals = new double[dimensions[0]][dimensions[1]];
        double cellWidth, cellHeight;
        int pixWidth, pixHeight;

        cellWidth = rvPanel.getWidth() / dimensions[0];
        cellHeight = rvPanel.getHeight() / dimensions[1];
        pixWidth = (int) cellWidth;
        pixHeight = (int) cellHeight;

        try {
            ary = (ArrayDouble.D2) values.read();

            int counter = 0;
            int x = 0, y = 0;
            IndexIterator it = ary.getIndexIterator();

            while (it.hasNext()) {
                vals[x][y] = (double) it.next();
                if (vals[x][y] > max) {
                    max = vals[x][y];
                }

                if (vals[x][y] < min) {
                    min = vals[x][y];
                }
                ++x;
                if (x == dimensions[0]) {
                    x = 0;
                    ++y;
                }

            } // end while
            double absRange = max - min;
            double ratio;
            double adjustedVal;
            int index;
            if (absRange == 0) {
                System.err.println("No variation in values");
            } else {

                rvPanel.setVisible(true);
                System.err.println("About to draw");
                for (int i = 0; i < dimensions[0]; ++i) {
                    for (int j = 0; j < dimensions[1]; ++j) {
                        adjustedVal = vals[i][j] - min;

                        ratio = (adjustedVal / absRange) * 20;

                        index = (int) ratio;

                        graphics.setColor(rvColor[index]);
                        graphics.fill3DRect(x * pixWidth, y * pixHeight, pixWidth, pixHeight, true);
                    }
                    System.err.println("Finished a row");
                }

                graphics.setColor(rvColor[10]);
                graphics.fill3DRect(0, 0, 100, 100, true);
                graphics.fill3DRect(500, 500, 500, 500, true);
                graphics.fillRect(0, 0, 100, 100);
                graphics.fillRect(500, 500, 500, 500);
                graphics.fill3DRect(0, 0, 100, 100, true);
//                rvPanel.paintComponents(graphics);
//                rvPanel.repaint();
                System.err.println("Finished drawing");
            }
        } catch (IOException ex) {
            Logger.getLogger(ResultsViewer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @name ResultsViewer Creates new form ResultsViewer
     */
    public ResultsViewer(UIPrototype1 parent) {
        ui = parent;
        chooser = new resultsChooser(this, true);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        returnButton = new javax.swing.JButton();
        selectButton = new javax.swing.JButton();
        rvPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        returnButton.setText("Return");
        returnButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                returnButtonActionPerformed(evt);
            }
        });

        selectButton.setText("Select Results File");
        selectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout rvPanelLayout = new javax.swing.GroupLayout(rvPanel);
        rvPanel.setLayout(rvPanelLayout);
        rvPanelLayout.setHorizontalGroup(
            rvPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        rvPanelLayout.setVerticalGroup(
            rvPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 332, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rvPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(returnButton)
                            .addComponent(selectButton))
                        .addGap(0, 487, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(selectButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rvPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(returnButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void returnButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_returnButtonActionPerformed

        // TODO add your handling code here:
        this.setVisible(false);
        ui.setVisible(true);
    }//GEN-LAST:event_returnButtonActionPerformed

    private void selectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectButtonActionPerformed
        // TODO add your handling code here:
        chooser.setVisible(true);
    }//GEN-LAST:event_selectButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ResultsViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ResultsViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ResultsViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ResultsViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ResultsViewer(new UIPrototype1()).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton returnButton;
    private javax.swing.JPanel rvPanel;
    private javax.swing.JButton selectButton;
    // End of variables declaration//GEN-END:variables
}
